import base64


def image_to_base64(image_path):
    """
    将图片文件转换为Base64字符串
    :param image_path: 图片文件路径
    :return: Base64编码字符串（不含Data URL前缀）
    """
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')


# 如果要生成完整的Data URL（可直接用于HTML）：
def image_to_data_url(image_path):
    """
    生成可直接用于HTML的Data URL
    :param image_path: 图片文件路径
    :return: data:image/...;base64,... 格式字符串
    """
    ext = image_path.split('.')[-1].lower()
    mime_type = f"image/{'jpeg' if ext == 'jpg' else ext}"  # 处理jpg的特殊情况
    base64_str = image_to_base64(image_path)
    return f"data:{mime_type};base64,{base64_str}"


# 使用示例
if __name__ == "__main__":
    img_path = r"D:\PythonProject\CanvasEdit\backend\media\images\default.png"

    # 获取纯Base64
    base64_str = image_to_base64(img_path)
    print(f"Base64字符串（前50字符）: {base64_str[:50]}...")

    # 获取完整Data URL
    data_url = image_to_data_url(img_path)
    print(f"\nData URL（前80字符）:\n{data_url[:80]}...")
    with open(r"D:\temp\output_base64.txt", "w") as f:
        f.write(data_url)